<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>委托管理</span>
      </div>
    </template>


    <!-- 新增双图表容器 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <div ref="chartRef1" style="width: 100%; height: 400px;"></div>
      </el-col>
      <el-col :span="12">
        <div ref="chartRef2" style="width: 100%; height: 400px;"></div>
      </el-col>
    </el-row>

    <!-- 表格内容 -->
    <el-table :data="ListData" v-if="false" style="width: 100%" v-loading="loading">
      <el-table-column label="序号" width="70" type="index" />

      <el-table-column label="总金额" prop="totalHouseFee" />
      <el-table-column label="总中介费金额" prop="totalServiceFee" />
      <el-table-column label="月份" prop="yuefenAll" />

      <template #empty>
        <el-empty description="暂无用户数据" />
      </template>
    </el-table>


    <!--   合同信息-->
    <div>
      <h2 >合同信息</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="contractListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="客户昵称" prop="username" />
          <el-table-column label="房东昵称" prop="landlordname" />
          <el-table-column label="签约时间" prop="createTime" />
          <el-table-column label="到期时间" prop="endTime" />
          <el-table-column label="服务费" prop="intAmount" />
          <el-table-column label="房源费用" prop="houseAmount" />
          <el-table-column label="房源类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'info',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    "0": '卖房',
                    "1": '租房',
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预约状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info'
            }[row.status]"
              >
                {{
                  {
                    0: '未支付',
                    1: '已生效',
                    2: '已失效'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="合同信息" prop="content">
            <template #default="{ row }">
              <el-button
                  v-if="row.content"
                  type="primary"
                  link
                  @click="downloadContract(row.content)"
              >
                下载合同
              </el-button>
              <span v-else>无合同文件</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button
                  type="success"
                  :icon="Check"
                  circle
                  plain
                  @click="edithetong(row)"
              ></el-button>
              <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  plain
                  @click="handleCancelhetong(row)"
              ></el-button>
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
        </el-table>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum3"
            v-model:page-size="pageSize3"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total3"
            @size-change="onSizeChange3"
            @current-change="onCurrentChange3"
            style="margin-top: 20px; justify-content: flex-end"
        />

      </el-row>

    </div>

    <router-view></router-view>
  </el-card>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {getIntList} from "@/api/user.js";
import {deleteContractService, getContractFinanciallist, getContractPageList, updateContract} from "@/api/contract.js";
import * as echarts from 'echarts'
import { useUserInfoStore } from "@/stores/userinfo.js";
import {Check, Close} from "@element-plus/icons-vue";
const userInfoStore = useUserInfoStore()
const userinfoId = userInfoStore.info.id;

const ListData = ref([])
const pageNum = ref(1)
const total = ref(0)
const pageSize = ref(15)
const searchForm = ref({ intermediaryId: userinfoId})
const loading = ref(false)

const IntListOptions = ref([])
const contractListData = ref([])
// 分页条数据模型
const pageNum3 = ref(1) // 当前页
const total3 = ref(0) // 总条数
const pageSize3 = ref(15) // 每页条数

const onSizeChange3 = (size) => {
  pageSize3.value = size
  // 重新获取数据
  contractListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange3 = (num) => {
  pageNum3.value = num
  // 重新获取数据
  contractListArray()
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const resint = await getIntList()
    IntListOptions.value = resint.res.map(item => ({
      value: item.id,
      label: item.nickname
    }))
  } catch (error) {
    console.error('获取失败:', error)
    ElMessage.error('加载失败')
  }
}

const downloadContract = (url) => {
  if (!url) {
    ElMessage.error('合同文件不存在');
    return;
  }

  // 如果URL是完整路径直接下载
  if (url.startsWith('http')) {
    window.open(url);
    return;
  }

  // 如果URL是相对路径，拼接基础URL（根据你的实际接口调整）
  const fullUrl = `http://your-api-domain.com${url}`;

  // 使用axios下载（需要处理跨域和认证时）
  axios({
    url: fullUrl,
    method: 'GET',
    responseType: 'blob',
    headers: {
      'Authorization': tokenStore.token // 如果需要认证
    }
  }).then(response => {
    const blob = new Blob([response.data]);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = url.split('/').pop() || 'contract';
    link.click();
    URL.revokeObjectURL(link.href);
  }).catch(error => {
    ElMessage.error('文件下载失败');
    console.error('下载失败:', error);
  });
}
// 新增图表相关
const chartRef = ref(null)
let chartInstance = null
// 图表相关修改
const chartRef1 = ref(null)
const chartRef2 = ref(null)
let chartInstance1 = null
let chartInstance2 = null
const searchFormhetong = ref({intermediaryId:userinfoId,type:'' })
// 初始化图表
const initCharts = () => {
  if (!chartRef1.value || !chartRef2.value || ListData.value.length === 0) return

  // 公共数据处理
  const sortedData = [...ListData.value].sort((a, b) =>
      a.yuefenAll.localeCompare(b.yuefenAll)
  )
  const xData = sortedData.map(item => item.yuefenAll)
  const houseFeeData = sortedData.map(item => item.totalHouseFee)
  const serviceFeeData = sortedData.map(item => item.totalServiceFee)

  // 总金额图表配置（柱状图）
  const houseOption = {
    title: {
      text: '月度总金额统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [{
      name: '总金额',
      type: 'bar',
      data: houseFeeData,
      itemStyle: {
        color: '#5470c6'
      }
    }]
  }

  // 中介费图表配置（折线图）
  const serviceOption = {
    title: {
      text: '月度中介费统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [{
      name: '中介费',
      type: 'line',
      smooth: true,
      data: serviceFeeData,
      itemStyle: {
        color: '#91cc75'
      }
    }]
  }

  // 初始化或更新图表
  if (!chartInstance1) {
    chartInstance1 = echarts.init(chartRef1.value)
    window.addEventListener('resize', () => chartInstance1.resize())
  }
  if (!chartInstance2) {
    chartInstance2 = echarts.init(chartRef2.value)
    window.addEventListener('resize', () => chartInstance2.resize())
  }

  chartInstance1.setOption(houseOption)
  chartInstance2.setOption(serviceOption)
}

// 修改监听和初始化部分
watch(ListData, () => {
  nextTick(() => initCharts())
})

onMounted(() => {
  initCharts()
})


// 获取列表数据
const ListArray = async () => {
  loading.value = true
  const params = {
    ...searchForm.value
  };
  try {
    const result = await getContractFinanciallist(
        params
    )
    ListData.value = result.res
    nextTick(() => initChart())
  } finally {
    loading.value = false
  }
}
const contractListArray = async () => {
  loading.value = true
  const params = {
    ...searchFormhetong.value,
  };
  try {
    const result = await getContractPageList(
        pageNum3.value,
        pageSize3.value,
        params
    )
    contractListData.value = result.res.items
    total3.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}


const handleCancelhetong = (row) => {
  ElMessageBox.confirm('此操作删除合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteContractService(row.id)
    ElMessage.success('删除成功')
    ListArray()
    contractListArray()
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
const edithetong = (row) => {
  ElMessageBox.confirm('确定收款后合同生效, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateContract({
      id:row.id
    })
    ListArray()
    contractListArray();
    ElMessage.success('合同已生效')
    ListArray()
  }).catch(() => {
    // ElMessage.info('取消操作')
  })
}


contractListArray()
// 初始加载
ListArray()
fetchDropdownOptions()

</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-tag {
    margin: 2px;
  }
}
/* 添加图表容器间距 */
.el-col {
  padding: 0 10px;
}
/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
